"use strict";

const {Service} = require("egg");
const {MyClass} = require("../entity/myentity");
const t = "classService：";

class classService extends Service {
  /**
   * @description: 添加一个班级
   * @param {string} className 班级名
   * @param {string} classHead 班级头像（可选）
   * @param {number} u_id 创建者的id
   */
  async add(className, classHead, u_id) {
    const {app, ctx} = this;
    const time = ctx.helper.parseTime(new Date());
    let ahead = "/public/image/class_head.png";
    if (classHead !== "" && classHead !== null && classHead !== undefined) {
      ahead = classHead;
    }
    const conn = await app.mysql.beginTransaction();
    try {
      const queryClass = await conn.get("my_class", {name: className});
      // console.log(t+queryClass);
      if (queryClass != null) {
        ctx.logger.error(`班级${queryClass.name}已存在，id为${queryClass.id}`);
        await conn.rollback();
        return {suc: false, msg: "该班级已存在"};
      }
      const createClass = await conn.insert("my_class", {
        name: className,
        head: ahead,
        create_time: time,
        code: ctx.helper.getRandomCode(),
      });
      // console.log(createClass.insertId);
      await conn.insert("u_class", {
        u_id: u_id,
        c_id: createClass.insertId,
        // 创建者默认为班级的老师
        isTeacher: true,
        in_review:false
      });
      const clss = await conn.get("my_class", {id: createClass.insertId});
      await conn.insert("class_log", {
        date: ctx.helper.parseTime(new Date()),
        description: "创建了班级",
        c_id: createClass.insertId,
        u_id: u_id,
      });
      await conn.commit();
      ctx.logger.info(`${u_id}创建了班级${createClass.insertId}`);
      return {suc: true, msg: "添加班级成功", data: clss};
    } catch (error) {
      ctx.logger.error(error);
      await conn.rollback();
      return {suc: false, msg: error};
    }
  }

  /**
   * @description: 将某个用户添加到某个班级
   * @param {number} u_id 用户的id
   * @param {number} c_id 班级的id
   * @param {boolean} isTeacher 是否是老师
   * @param {boolean} in_review 是否正在审核
   */
  async joinClass(u_id, c_id, isTeacher,in_review) {
    const {app, ctx} = this;
    const conn = await app.mysql.beginTransaction();
    try {
      const data = {
        u_id: u_id,
        c_id: c_id,
        isTeacher: isTeacher,
        in_review:in_review
      };
      const queryStudent = await conn.get("u_class", data);
      // console.log(queryStudent)
      if (queryStudent != null) {
        ctx.logger.error(`用户${u_id}已经加入班级${c_id}`);
        return {suc: false, msg: "已经加入该班级"};
      }

      await conn.insert("u_class", data);
      let queryClass = await conn.get("my_class", {id: data.c_id});
      await conn.insert("class_log", {
        date: ctx.helper.parseTime(new Date()),
        description: "加入了班级",
        c_id: c_id,
        u_id: u_id,
      });
      await conn.commit();
      ctx.logger.info(`用户${u_id}加入了班级${c_id}`);
      return {suc: true, msg: "加入班级成功"};
    } catch (error) {
      ctx.logger.error(error);
      await conn.rollback();
      return {suc: false, err: error};
    }
  }

  /**
   * @description: 使一个用户退出班级
   * @param {number} u_id 用户的id
   * @param {number} c_id 班级的id
   */
  async exitClass(u_id, c_id) {
    const {app, ctx} = this;
    try {
      const data = {u_id, c_id};
      const queryClass = await app.mysql.get("my_class", {id: c_id});
      if (queryClass != null) {
        await app.mysql.insert("class_log", {
          date: ctx.helper.parseTime(new Date()),
          description: "退出了班级",
          c_id: c_id,
          u_id: u_id,
        });
      }
      await app.mysql.delete("u_class", data);
      ctx.logger.info(`用户${u_id}退出了班级${c_id}`);
      return {suc: true, msg: "退出班级成功"};
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, err: error};
    }
  }

  /**
   * @description: 删除某个班级
   * @param id
   */
  async del(id) {
    const {app, ctx} = this;
    try {
      await app.mysql.delete("my_class", {id});
      ctx.logger.info(`删除了班级${id}`);
      return {suc: true, msg: "删除班级成功"};
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  /**
   * @description: 更新班级信息
   * @param {MyClass} newClass 要更新的班级信息
   */
  async update(newClass) {
    const {app, ctx} = this;
    try {
      await app.mysql.update("my_class", newClass);
      const classInfo = await app.mysql.get("my_class", newClass.id);
      ctx.logger.info(`班级${newClass.id}被更新`);
      return {suc: true, data: classInfo, msg: "更新班级信息成功"};
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  /**
   * @description: 更新班级名
   * @param {MyClass} newClass 新的班级
   */
  async updateName(newClass) {
    const {app, ctx} = this;
    try {
      let query = await app.mysql.get("my_class", {name: newClass.name});
      if (query != null) {
        ctx.logger.error(`班级${query.name}已存在，id为${query.id}`);
        return {suc: false, msg: "该班级名已存在"};
      }
      await app.mysql.update("my_class", newClass);
      query = await app.mysql.get("my_class", newClass);
      ctx.logger.info(`班级${newClass.id}被更新`);
      return {suc: true, data: query, msg: "更新班级信息成功"};
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  /**
   * @description: 查询一个班级
   * @param {Class} mclass 班级
   */
  async getOne(mclass) {
    const {app, ctx} = this;
    try {
      const query = await app.mysql.get("my_class", mclass);
      if(query != null){
        ctx.logger.info(`班级${query.id}被查询`);
      }else{
        ctx.logger.info(`没有查到任何班级`);
      }
      return {data: query, suc: true, msg: "查询一个班级成功"};
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  /**
   * @description: 查询某个用户加入的全部班级
   * @param {number} u_id 用户id
   */
  async userGetAll(u_id) {
    const {app, ctx} = this;
    try {
      const query = [];
      /**
       * @type {UserClass[]}
       */
      const queryUserClass = await app.mysql.select("u_class", {
        where: {u_id:u_id,in_review:false},
      });
      for (const i in queryUserClass) {
        const data = await app.mysql.get("my_class", {
          id: queryUserClass[i].c_id,
        });
        query.push(data);
        ctx.logger.info(`班级${queryUserClass[i].c_id}被查询`);
      }
      return {data: query, suc: true, msg: "查询该用户全部班级成功"};
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  /**
   * 获取用户管理的全部班级
   * @param {number} u_id
   */
  async userManageClass(u_id) {
    const {app, ctx} = this
    try {
      /**
       * @type {UserClass[]}
       */
      let queryUserClass = await app.mysql.select("u_class", {where: {u_id: u_id, isTeacher: true,in_review:false}});
      //console.log(queryUserClass)
      let list = []
      for (let i in queryUserClass) {
        let uClass = queryUserClass[i];
        let manageClass = await app.mysql.get("my_class", {id: uClass.c_id});
        if (manageClass != null) {
          list.push(manageClass);
        }
      }
      return {suc: true, msg: "获取用户管理的全部班级成功", data: list}
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  //查询当前班级是否由用户管理
  async isUserManage(u_id, c_id) {
    const {app, ctx} = this
    try {
      /**
       * @type {UserClass}
       */
      let query = await app.mysql.get("u_class", {u_id: u_id, c_id: c_id});
      let result = false;
      if(query.isTeacher && !query.in_review){
        result = true
      }
      return {data: result, msg: "查询成功", suc: true}
    } catch (error) {
      ctx.logger.error(error);
      return {suc: false, msg: error};
    }
  }

  /**
   * 查询某个班级全部的用户
   * @param {number} id 班级id
   */
  async getClassAllUser(id) {
    const {app} = this
    const conn = await app.mysql.beginTransaction()
    try {
      /**
       * 查询该班级与用户的关联表
       * @type {UserClass[]}
       */
      let allUClass = await conn.select('u_class', {where: {c_id: id,in_review:false}})
      /**
       * 查询到的用户存储在这里
       * @type {User[]}
       */
      let userList = []
      //遍历查询用户
      for (let i in allUClass) {
        let u_class = allUClass[i];
        let userId = u_class.u_id;
        /**@type {User}*/
        let user = await conn.get("user", {id: userId});
        userList.push(user);
      }
      app.logger.info(`查询班级${id}的全部用户`)
      await conn.commit();
      return {data:userList,msg:'查询班级全部用户成功',suc:true}
    } catch (e) {
      await conn.rollback();
      app.logger.error(e);
      console.error(e);
      return {suc:false,msg:e}
    }
  }

  /**
   * 查询某个班级全部的管理员
   * @param {number} id 班级id
   */
  async getClassAllAdmin(id) {
    const {app} = this
    const conn = await app.mysql.beginTransaction()
    try {
      /**
       * 查询该班级与用户的关联表
       * @type {UserClass[]}
       */
      let allUClass = await conn.select('u_class', {where: {c_id: id,isTeacher:true,in_review:false}})
      /**
       * 查询到的用户存储在这里
       * @type {User[]}
       */
      let userList = []
      //遍历查询用户
      for (let i in allUClass) {
        let u_class = allUClass[i];
        let userId = u_class.u_id;
        /**@type {User}*/
        let user = await conn.get("user", {id: userId});
        userList.push(user);
      }
      app.logger.info(`查询班级${id}的全部用户`)
      await conn.commit();
      return {data:userList,msg:'查询班级全部用户成功',suc:true}
    } catch (e) {
      await conn.rollback();
      app.logger.error(e);
      console.error(e);
      return {suc:false,msg:e}
    }
  }

  /**
   * 同意用户加入班级
   * @param {number}u_id1 被操作的用户id
   * @param {number}c_id 对应班级id
   * @param {number}u_id2 操作者id
   * @returns {Promise<void>}
   */
  async confirmUserJoin(u_id1,c_id,u_id2){
    const {app} = this
    const conn = await app.mysql.beginTransaction()
    let ret = {suc:false,msg:"",data:null}
    try {
      /**
       * 查找user是否提交申请
       * @type {UserClass}
       */
      let find = await conn.get("u_class",{u_id:u_id1,c_id:c_id})
      if(find == null){
        await conn.rollback();
        app.logger.warn("用户没有提交申请")
        ret.msg = "用户没有提交申请"
      }else{
        await conn.update("u_class",{id:find.id,c_id:c_id,u_id:u_id1,in_review:false})
      }
      return ret
    }catch (e) {
      await conn.rollback()
      app.logger.error(e)
      ret.msg= e
      return ret
    }
  }

}


module.exports = classService;
